import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'; 
import VueRouter from 'vue-router';
import GlobalFooter from './components/Footer.vue';

// 配置全局设置
Vue.config.productionTip = false
Vue.use(ElementUI);
Vue.component('GlobalFooter', GlobalFooter);

// 重写路由方法，解决重复导航错误
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err;
    }
  });
};

VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err;
    }
  });
};

// 页面初始化函数（包含WebSocket初始化）
async function initApp() {
  try {
    // 1. 先初始化认证状态
    await store.dispatch('manager/initAuth');
    
    // 2. 若token存在，初始化WebSocket连接
    if (store.getters['manager/token']) {
      console.log('检测到有效token，初始化WebSocket连接');
      await store.dispatch('manager/initWebSocket');
    } else {
      console.log('未检测到token，跳过WebSocket初始化');
    }
  } catch (error) {
    console.error('应用初始化失败:', error);
  }
}

// 先执行初始化逻辑，再创建Vue实例
initApp().then(() => {
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount('#app');
});